<template>
    <div class="login-page">
        <el-form ref="ruleFormRef" style="width: 400px" :model="ruleForm" :rules="rules" label-width="auto"
            class="demo-ruleForm" status-icon>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import request from '@/utils/request';
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
const router = useRouter()

const ruleFormRef = ref()
const ruleForm = reactive({
    username: '',
    password: ''
})

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 5, message: '内容在3-5个字之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 5, message: '内容在3-5个字之间', trigger: 'blur' },
    ],
})
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            request.post('/login', ruleForm).then(res => {
                console.log(res);
                if (res.status === 200 && res.data.code === 10000) {
                    // 存储两个token、头像、用户
                    localStorage.setItem('accessToken', res.data.data.accessToken)
                    localStorage.setItem('refreshToken', res.data.data.refreshToken)
                    localStorage.setItem('avator', res.data.data.userInfo.avator)
                    localStorage.setItem('role', res.data.data.userInfo.username)
                    // 跳转首页
                    router.push({
                        path: '/'
                    })
                    // 登陆成功时的消息提示
                    ElMessage({
                        message: res.data.message,
                        type: 'success',
                    })
                } else {
                    // 登录失败时提示
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>

<style scoped>
.login-page {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>